//
//  LYHUDUtils.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/20.
//

import UIKit
import MBProgressHUD

class LYHUDUtils {
    
    // MARK: - 私有属性
    private static var currentLoadingHUD: MBProgressHUD?
    
    // MARK: - Toast 提示（自动消失）
    static func showToast(_ message: String,
                         duration: TimeInterval = 2.0,
                         in view: UIView? = nil,
                         hideLoading: Bool = true) {
//        DispatchQueue.main.async {
            guard let targetView = view ?? UIApplication.shared.currentKeyWindow else { return }
            
            // 如果需要，先隐藏Loading
            if hideLoading {
                hideHUD()
            }
            
            let hud = MBProgressHUD.showAdded(to: targetView, animated: true)
            hud.mode = .text
            hud.label.text = message
            hud.label.numberOfLines = 0
            hud.removeFromSuperViewOnHide = true
            hud.bezelView.style = .solidColor
            hud.bezelView.color = UIColor(hex: "#000000", alpha: 0.6)
            hud.label.textColor = UIColor(hex: "#FFFFFF")
            hud.hide(animated: true, afterDelay: duration)
//        }
    }
    
    // MARK: - Loading 加载中（需手动隐藏）
    static func showLoading(_ message: String? = nil,
                            in view: UIView? = nil) {
        DispatchQueue.main.async {
            guard let targetView = view ?? UIApplication.shared.currentKeyWindow else { return }
            
            // 先隐藏现有的Loading
            hideHUD()
            
            let hud = MBProgressHUD.showAdded(to: targetView, animated: true)
            hud.mode = .indeterminate
            hud.label.text = message
            hud.bezelView.style = .solidColor
            hud.bezelView.color = UIColor(hex: "#000000", alpha: 0.6)
            hud.label.textColor = UIColor(hex: "#FFFFFF")
            hud.removeFromSuperViewOnHide = true
            
            // 保存当前Loading引用
            currentLoadingHUD = hud
        }
    }
    
    // MARK: - 隐藏 HUD
    static func hideHUD(for view: UIView? = nil) {
        // 隐藏特定视图或当前Loading
        if let targetView = view ?? UIApplication.shared.currentKeyWindow {
            MBProgressHUD.hide(for: targetView, animated: true)
        }
        
        // 清除当前Loading引用
        currentLoadingHUD = nil
    }
}
